package com.easy.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easy.common.core.domain.entity.User;
import com.easy.common.utils.ServletUtils;
import com.easy.common.utils.ip.IpOrAddress;
import com.easy.user.mapper.UserLogMapper;
import com.easy.user.mapper.UserLoginMapper;
import com.easy.user.pojo.LoginInfo;
import com.easy.user.service.LoginInfoService;
import com.easy.user.service.UserLogService;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class UserLogServiceImpl extends ServiceImpl<UserLoginMapper, User> implements UserLogService {
    @Autowired
    private UserLogMapper userLogMapper;

    @Autowired
    private LoginInfoService loginInfoService;

    /**
     * 更新登录地址和ip
     *
     * @param user 用户
     */
    @Override
    public void updateLoginAddressAndIp(User user) {
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getId, user.getId());
        updateWrapper.set(User::getLoginTime, LocalDateTime.now());
        updateWrapper.set(User::getLoginLocation, IpOrAddress.getIp() + IpOrAddress.getAddress());
        userLogMapper.update(null, updateWrapper);
    }

    /**
     * 添加 登录 日志
     *
     * @param user 用户
     */
    @Override
    public void addLoginLog(User user) {
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setUserId(user.getId());
        loginInfo.setUserName(user.getUserName());
        loginInfo.setUserType(user.getType());
        loginInfo.setIpaddr(IpOrAddress.getIp());
        loginInfo.setLoginLocation(IpOrAddress.getAddress());
        loginInfo.setLoginTime(LocalDateTime.now());
        loginInfo.setBrowser(userAgent.getBrowser().getName());
        loginInfo.setStatus(user.getStatus());
        loginInfoService.save(loginInfo);/**/
    }
}
